import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';

class AreaPicker extends StatefulWidget {
  final String? initialProvince;
  final String? initialCity;
  final String? initialDistrict;
  final Function(String province, String city, String district) onConfirm;
  final List<Map<String, dynamic>> areaData;

  const AreaPicker({
    super.key,
    this.initialProvince,
    this.initialCity,
    this.initialDistrict,
    required this.onConfirm,
    required this.areaData,
  });

  @override
  State<AreaPicker> createState() => _AreaPickerState();
}

class _AreaPickerState extends State<AreaPicker> {
  int provinceIndex = 0;
  int cityIndex = 0;
  int districtIndex = 0;

  late FixedExtentScrollController provinceController;
  late FixedExtentScrollController cityController;
  late FixedExtentScrollController districtController;

  List<Map<String, dynamic>> get provinces => widget.areaData;
  List<Map<String, dynamic>> get cities =>
      provinces.isNotEmpty && provinceIndex < provinces.length
          ? List<Map<String, dynamic>>.from(
              provinces[provinceIndex]['children'] ?? [])
          : [];
  List<Map<String, dynamic>> get districts =>
      cities.isNotEmpty && cityIndex < cities.length
          ? List<Map<String, dynamic>>.from(cities[cityIndex]['children'] ?? [])
          : [];

  @override
  void initState() {
    super.initState();
    _initializeIndexes();
    provinceController = FixedExtentScrollController(initialItem: provinceIndex);
    cityController = FixedExtentScrollController(initialItem: cityIndex);
    districtController = FixedExtentScrollController(initialItem: districtIndex);
  }

  void _initializeIndexes() {
    if (widget.initialProvince != null) {
      provinceIndex = provinces.indexWhere(
          (p) => p['name'] == widget.initialProvince);
      if (provinceIndex == -1) provinceIndex = 0;

      if (widget.initialCity != null) {
        cityIndex = cities.indexWhere((c) => c['name'] == widget.initialCity);
        if (cityIndex == -1) cityIndex = 0;

        if (widget.initialDistrict != null) {
          districtIndex = districts
              .indexWhere((d) => d['name'] == widget.initialDistrict);
          if (districtIndex == -1) districtIndex = 0;
        }
      }
    }
  }

  @override
  void dispose() {
    provinceController.dispose();
    cityController.dispose();
    districtController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 300.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282725),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(24.r),
          topRight: Radius.circular(24.r),
        ),
      ),
      child: Column(
        children: [
          _buildHeader(),
          Expanded(
            child: Row(
              children: [
                Expanded(child: _buildColumn(provinces, provinceController, 0)),
                Expanded(child: _buildColumn(cities, cityController, 1)),
                Expanded(child: _buildColumn(districts, districtController, 2)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Color(0xFF3A3A3A), width: 1),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          GestureDetector(
            onTap: () => Get.back(),
            child: Text(
              '取消',
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.grey[400],
              ),
            ),
          ),
          Text(
            '选择地区',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.w500,
              color: Colors.white,
            ),
          ),
          GestureDetector(
            onTap: _onConfirm,
            child: Text(
              '确定',
              style: TextStyle(
                fontSize: 14.sp,
                color: const Color(0xFFF67F41),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildColumn(List<Map<String, dynamic>> items,
      FixedExtentScrollController controller, int type) {
    if (items.isEmpty) {
      return Center(
        child: Text(
          '暂无数据',
          style: TextStyle(
            fontSize: 14.sp,
            color: Colors.grey[500],
          ),
        ),
      );
    }

    return ListWheelScrollView.useDelegate(
      controller: controller,
      itemExtent: 40.h,
      physics: const FixedExtentScrollPhysics(),
      onSelectedItemChanged: (index) {
        setState(() {
          if (type == 0) {
            provinceIndex = index;
            cityIndex = 0;
            districtIndex = 0;
            cityController.jumpToItem(0);
            districtController.jumpToItem(0);
          } else if (type == 1) {
            cityIndex = index;
            districtIndex = 0;
            districtController.jumpToItem(0);
          } else {
            districtIndex = index;
          }
        });
      },
      childDelegate: ListWheelChildBuilderDelegate(
        builder: (context, index) {
          final isSelected = (type == 0 && index == provinceIndex) ||
              (type == 1 && index == cityIndex) ||
              (type == 2 && index == districtIndex);

          return Center(
            child: Text(
              items[index]['name'] ?? '',
              style: TextStyle(
                fontSize: isSelected ? 16.sp : 14.sp,
                color: isSelected ? Colors.white : Colors.grey[500],
                fontWeight: isSelected ? FontWeight.w500 : FontWeight.normal,
              ),
            ),
          );
        },
        childCount: items.length,
      ),
    );
  }

  void _onConfirm() {
    if (provinces.isEmpty) return;

    final province = provinces[provinceIndex]['name'] ?? '';
    final city = cities.isNotEmpty ? cities[cityIndex]['name'] ?? '' : '';
    final district =
        districts.isNotEmpty ? districts[districtIndex]['name'] ?? '' : '';

    widget.onConfirm(province, city, district);
    Get.back();
  }
}
